package com.jzg.jcptadmin.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.MD5Utils;
import com.jzg.jcptadmin.Utils.MyToast;
import com.jzg.jcptadmin.Utils.UIUtils;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.constant.Constant;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.local.ACache;
import com.jzg.jcptadmin.data.vo.City;
import com.jzg.jcptadmin.data.vo.OffonlineTaskData;
import com.jzg.jcptadmin.data.vo.Province;
import com.jzg.jcptadmin.data.vo.SuccessData;
import com.jzg.jcptadmin.data.vo.User;
import com.jzg.jcptadmin.presenter.OffOnlineTaskPresenter;
import com.jzg.jcptadmin.viewinterface.OffonLineTaskInterface;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * 线下任务界面
 * OffonlineTaskActivity
 *
 * @author sunbl
 *         created at 2016/4/1 11:23
 */
public class OffonlineTaskActivity extends BaseActivity implements View.OnClickListener, OffonLineTaskInterface {

    @Bind(R.id.tv_lianxiren)
    TextView tvLianxiren;
    @Bind(R.id.tv_mlianxiren)
    EditText tvMlianxiren;
    @Bind(R.id.lianxiren_relative)
    RelativeLayout lianxirenRelative;
    @Bind(R.id.tv_phone)
    TextView tvPhone;
    @Bind(R.id.tv_mphone)
    EditText tvMphone;
    @Bind(R.id.phone_relative)
    RelativeLayout phoneRelative;
    @Bind(R.id.tv_area)
    TextView tvArea;
    @Bind(R.id.et_area)
    EditText etArea;
    @Bind(R.id.area_relative)
    RelativeLayout areaRelative;
    @Bind(R.id.cheliang)
    TextView cheliang;
    @Bind(R.id.cheliangshow)
    EditText cheliangshow;
    @Bind(R.id.chengjiaojia_relative)
    RelativeLayout chengjiaojiaRelative;
    @Bind(R.id.tv_beizhu)
    TextView tvBeizhu;
    @Bind(R.id.et_beizhu)
    EditText etBeizhu;
    @Bind(R.id.save)
    TextView save;
    @Bind(R.id.submit)
    TextView Submit;
    @Bind(R.id.area_content)
    TextView areaContent;
    @Bind(R.id.area_layout)
    RelativeLayout areaLayout;
    private OffonlineTaskData offonlineTaskData;
    private OffOnlineTaskPresenter offOnlineTaskPresenter;
    private User user;
    private int isInitData = 0;//是否初始化缓存数据,1提交成功后的缓存,不缓存车辆数,-1保存的时候取消了,0默认
    //选择信息广播接收器
    private SelectInfoReceiver selectInfoReceiver;
    //省
    private Province province;

    //市
    private City city;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_offonline_task);
        ButterKnife.bind(this);
        user = appContext.getUser();
        offOnlineTaskPresenter = new OffOnlineTaskPresenter(DataManager.getInstance());
        offOnlineTaskPresenter.attachView(this);
//        initView();
        //注册接受车辆选择和城市选择的广播接收器
        selectInfoReceiver = new SelectInfoReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.CITY_SELECT_BROADCAST);
        LocalBroadcastManager.getInstance(this).registerReceiver(selectInfoReceiver, filter);
        initData();
    }

    private void initData() {
        if (user.getSetArea() == 0) {
            UIUtils.disableSubControls(areaLayout);
        }
        offonlineTaskData = (OffonlineTaskData) ACache.get(this).getAsObject("offonlineTaskData"+user.getUserId());
        if (offonlineTaskData == null) {
            offonlineTaskData = new OffonlineTaskData();
        }
        tvMlianxiren.setText(offonlineTaskData.getPhoneName());
        tvMphone.setText(offonlineTaskData.getPhoneNumber());
        etArea.setText(offonlineTaskData.getArea());
        cheliangshow.setText(offonlineTaskData.getCarCount());
        etBeizhu.setText(offonlineTaskData.getDes());
        if (!TextUtils.isEmpty(offonlineTaskData.getCityName())) {
            areaContent.setText(offonlineTaskData.getProvinceName() + "-" + offonlineTaskData.getCityName());
        } else {
            areaContent.setText(user.getProvinceName() + "-" + user.getCityName());
        }
        setEditTextCursorLocation(tvMlianxiren);//光标移动到最后一位
    }

    /**
     * 选择品牌、车系、车型、省、市广播接受
     */
    class SelectInfoReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            //城市选择接受数据
            if (intent.getAction().equals(Constant.CITY_SELECT_BROADCAST)) {
                city = intent.getParcelableExtra(Constant.CITY);
                province = intent.getParcelableExtra(Constant.PROVINCE);
                areaContent.setText(province.getName() + "-" + city.getName());
            }

        }
    }
//    private void initView() {
//        save.setOnClickListener(this);
//        Submit.setOnClickListener(this);
//
//    }

    private void submitData() {
        if (checkParmars()) {
            showDialog();
            offOnlineTaskPresenter.upLoadOffOnLineTaskData();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private boolean checkParmars() {
        String carOwner = tvMlianxiren.getText().toString();
        String iphone = tvMphone.getText().toString();
        String address = etArea.getText().toString();
        String carCount = cheliangshow.getText().toString();
        if (TextUtils.isEmpty(carOwner) && TextUtils.isEmpty(iphone)
                && TextUtils.isEmpty(address) && TextUtils.isEmpty(carCount)
                && TextUtils.isEmpty(etBeizhu.getText().toString())) {
            MyToast.showShort("您暂未输入任务信息！");
            return false;
        }
        if (TextUtils.isEmpty(carOwner)) {
            MyToast.showShort("联系人不能为空");
            return false;
        }
        if (TextUtils.isEmpty(iphone) || !isPhoneNumberValid(iphone)) {
            MyToast.showShort("请输入正确的联系电话");
            return false;
        }
        if (TextUtils.isEmpty(address)) {
            MyToast.showShort("地址不能为空");
            return false;
        }
        try {
            if (TextUtils.isEmpty(carCount) || Integer.parseInt(carCount) > 10) {
                MyToast.showShort("车辆不能大于10辆");
                return false;
            }
            if (Integer.parseInt(carCount) <= 0) {
                MyToast.showShort("车辆不能小于1辆");
                return false;
            }

        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        return true;
    }

    private boolean saveCheckParmars() {
        String carOwner = tvMlianxiren.getText().toString();
        String iphone = tvMphone.getText().toString();
        String address = etArea.getText().toString();
        String carCount = cheliangshow.getText().toString();

        if (!TextUtils.isEmpty(iphone) && !isPhoneNumberValid(iphone)) {
            MyToast.showShort("请输入正确的联系电话");
            return false;
        }

        try {
            if (TextUtils.isEmpty(carCount)) {
                return true;
            }
            if (!TextUtils.isEmpty(carCount) && Integer.parseInt(carCount) > 10) {
                MyToast.showShort("车辆不能大于10辆");
                return false;
            }
            if (Integer.parseInt(carCount) <= 0) {
                MyToast.showShort("车辆不能小于1辆");
                return false;
            }

        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        return true;
    }

    /**
     * 判断是否是手机号码
     */
    public static boolean isPhoneNumberValid(String phoneNumber) {
        boolean isValid = false;
        CharSequence inputStr = phoneNumber;
        Pattern p = Pattern
                .compile("^((13[0-9])|(15[^4,\\D])|(17[0,7])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(inputStr);
        if (m.matches()) {
            isValid = true;
        }
        return isValid;
    }

    @OnClick({R.id.save, R.id.submit, R.id.area_layout})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.save:
                save();
                break;
            case R.id.submit:
                submitData();
                break;
            case R.id.area_layout:
                Intent areaIntent = new Intent(this, AreaActivity.class);
                areaIntent.putExtra(Constant.KEY_TITLE,"选择地区");
                startActivity(areaIntent);
                break;
            default:
                break;
        }

    }

    private void save() {
        new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                .setTitleText("提示")
                .setContentText("您确定要保存这条数据吗？")
                .setConfirmText("是的").setCancelText("取消")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        if (saveCheckParmars()) {
                            MobclickAgent.onEvent(OffonlineTaskActivity.this,"jigou_xinjianxianxiabaocun");
                            Toast.makeText(OffonlineTaskActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            sDialog.dismissWithAnimation();
                        }
                    }
                }).setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                isInitData = -1;
                finish();
            }
        }).show();


    }

    @Override
    public Map<String, String> getParams() {
        Map<String, String> params = new HashMap<>();
        params.put("CarOwner", tvMlianxiren.getText().toString());
        params.put("tokenid", "6");
        params.put("Iphone", tvMphone.getText().toString());
        params.put("Address", etArea.getText().toString());
        params.put("TaskCarCount", cheliangshow.getText().toString());
        params.put("des", etBeizhu.getText().toString());
        params.put("userid", user.getUserId() + "");
        if (city != null) {
            params.put("cityid", city.getId() + "");
            params.put("provid", province.getId() + "");
        } else if (!TextUtils.isEmpty(offonlineTaskData.getCityName())) {
            params.put("cityid", offonlineTaskData.getCityId());
            params.put("provid", offonlineTaskData.getProvinceId());
        } else {
            params.put("cityid", user.getCityId() + "");
            params.put("provid", user.getProvinceId() + "");
        }
        Map<String, Object> maps = new HashMap<>();
        maps.putAll(params);
        params.put("sign", MD5Utils.getMD5Sign(maps));
        return params;
    }

    @Override
    public void showResult(SuccessData data) {
        dismissDialog();
//        if (data.getStatus() == 100) {
//            isInitData = 1;
//            Intent intent = new Intent(OffonlineTaskActivity.this, YiXinActivity.class);
//            intent.putExtra("title", "已完成");
//            startActivity(intent);
//            finish();
//        } else {
//            isInitData = 1;
//            Toast.makeText(OffonlineTaskActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
//        }

    }

    @Override
    public void showError(String error) {
        super.showError(error);
        dismissDialog();
        MyToast.showShort(error);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        if(selectInfoReceiver!=null){
            LocalBroadcastManager.getInstance(this).unregisterReceiver(selectInfoReceiver);
        }
        if(offOnlineTaskPresenter!=null){
            offOnlineTaskPresenter.detachView();
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (isInitData == 1) {//提交后缓存数据
            offonlineTaskData.setPhoneName(tvMlianxiren.getText().toString());
            offonlineTaskData.setPhoneNumber(tvMphone.getText().toString());
            offonlineTaskData.setArea(etArea.getText().toString());
            offonlineTaskData.setCarCount("");
            offonlineTaskData.setDes(etBeizhu.getText().toString());
            //if (city != null) {
                offonlineTaskData.setCityName(user.getCityName());
                offonlineTaskData.setCityId(user.getCityId() + "");
          //  }
           // if (province != null) {
                offonlineTaskData.setProvinceName(user.getProvinceName() + "");
                offonlineTaskData.setProvinceId(user.getProvinceId() + "");
           // }

        } else if (isInitData == -1) {//取消保存
            offonlineTaskData = new OffonlineTaskData();
        } else {
            offonlineTaskData.setPhoneName(tvMlianxiren.getText().toString());
            offonlineTaskData.setPhoneNumber(tvMphone.getText().toString());
            offonlineTaskData.setArea(etArea.getText().toString());
            offonlineTaskData.setCarCount(cheliangshow.getText().toString());
            offonlineTaskData.setDes(etBeizhu.getText().toString());
            if (city != null) {
                offonlineTaskData.setCityName(city.getName());
                offonlineTaskData.setCityId(city.getId() + "");
            }
            if (province != null) {
                offonlineTaskData.setProvinceName(province.getName() + "");
                offonlineTaskData.setProvinceId(province.getId() + "");
            }

        }
        ACache.get(this).put("offonlineTaskData"+user.getUserId(), offonlineTaskData);
    }

    public void setEditTextCursorLocation(EditText editText) {
        CharSequence text = editText.getText();
        if (text instanceof Spannable) {
            Spannable spanText = (Spannable) text;
            Selection.setSelection(spanText, text.length());
        }
    }
}
